package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.ClassHelper;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.entityVo.ShopVo;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.service.IShopService;
import com.antdesignbackend.backend.service.PermissionService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/shop")
public class ShopController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createTime=new Date();
    private Integer menuId;
    private Integer userId;
    private Integer userType;
    private String roleID;
    @Autowired
    private IShopService shopService;
    @Autowired
    private UserService userService;
    @Autowired
    PermissionService permissionService;
    /**
     * 商铺首页
     */
    @GetMapping("/index")
    @AuthToken
    public String index(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "shop/index";

    }

    /**
     * 权限查询
     */
    @GetMapping("/getPermission")
    @AuthToken
    @ResponseBody
    public List<Button> permission(HttpServletRequest request) {
        if (request.getSession().getAttribute("RoleID") != null) {
            roleID = request.getSession().getAttribute("RoleID").toString();
        }
        //得到当前菜单具备的功能权限
        List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
        return list;
    }


    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody ShopVo data,HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<ShopVo> datalist=new ArrayList<>();
        QueryWrapper<ShopVo> wrapper =new QueryWrapper<ShopVo>();

        //根据权限生成过滤条件
        if(roleID.equals("1") || roleID.equals("2"))
        {//管理员
        }
        else if(roleID.equals("3"))
        {//商户
           wrapper.inSql("t.userId","select userid from users where Activity=1 and UserID="+userId);
        }
        else
        {
            //否则不给数据
            wrapper.eq("userId",0);
        }
        //正常查询过滤条件
        if(data.getName()!=null && !data.getName().equals(""))
        {
            //  wrapper.and(wra -> wra.like("name", data.getName()).or().like("clientNo", data.getName()));
            wrapper.and(wra -> wra.like("name", data.getName()));
        }

        if(data.getState()!=null && !data.getState().equals(""))
        {
            wrapper.eq("state",data.getState());
        }

        if (data.getTypeofShop() != null && data.getTypeofShop() != -1){
            wrapper.eq("typeofShop",data.getTypeofShop());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=shopService.counts(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= shopService.searchs(wrapper.orderByAsc("name"),new Page<>(data.getPageIndex(),data.getPageSize()));
            //得到当前菜单具备的功能权限
//            List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//            datalist.forEach(model -> model.setButtonList(list));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 新增/修改保存
     * id 0是新增加，否则修改
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody ShopVo vo) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        Shop entity = new Shop();
        if(vo.getId()>0) {
            //先获取旧的数据集
            entity= shopService.getById(vo.getId());
        }
        if(vo.getAction().equals("change")) {
            entity.setState(vo.getState());
        }else {
            //新增，修改
            entity.setName(vo.getName());
            entity.setRate(vo.getRate());
            entity.setCharges(vo.getCharges());
            entity.setAddress(vo.getAddress());
            entity.setCreateTime(vo.getCreateTime());
            entity.setLat(vo.getLat());
            entity.setLng(vo.getLng());
            entity.setPhone(vo.getPhone());
            entity.setRemark(vo.getRemark());
            entity.setState(vo.getState());
            entity.setUserId(vo.getUserId());
            entity.setTypes(vo.getTypes());
            entity.setParentId(vo.getParentId());
            entity.setShopType(vo.getShopType());
            entity.setTags(vo.getTags());
            entity.setSpace(vo.getSpace());
            entity.setProvinceCode(vo.getProvinceCode());
            entity.setCityCode(vo.getCityCode());
            entity.setAreaCode(vo.getAreaCode());
            entity.setStartTime(vo.getStartTime());
            entity.setEndTime(vo.getEndTime());
            entity.setTypeofShop(vo.getTypeofShop());
        }
        if (vo.getId() == 0) {
            //新增
            entity.setMerchantType("4");
            entity.setNotityCode(ClassHelper.getRandomString(6));
            b = shopService.save(entity);
        }
        else{
            //修改
            b = shopService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 获得商户
     */
    @ResponseBody
    @GetMapping(value = "/getShopUser")
    @AuthToken
    public ReturnVO getShopUser(HttpServletRequest request) {
        result = new ReturnVO();
        QueryWrapper<Users> wrapper =new QueryWrapper<Users>();
        wrapper.eq("userType",4);
        wrapper.eq("types",1);
        wrapper.eq("activity",1);
        List<Users> dataList = userService.getBaseMapper().selectList(wrapper);
        result.setData(dataList);
        return result;
    }
    /***
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (shopService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            result.setCode("200");
        } else {
            result.setMessage("删除失败");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 获得所属商户
     */
    @ResponseBody
    @GetMapping(value = "/getServUser")
    @AuthToken
    public ReturnVO getServUser(HttpServletRequest request) {
        result = new ReturnVO();
        QueryWrapper<Users> wrapper =new QueryWrapper<Users>();
        wrapper.eq("userType",3);
        wrapper.eq("types",1);
        List<Users> dataList = userService.getBaseMapper().selectList(wrapper);
        result.setData(dataList);
        return result;
    }

    /**
     * 修改门店信息
     * @param shop
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    @AuthToken
    public ReturnVO update(@RequestBody Shop shop){
        try {
            if (!shopService.updateById(shop)){
                result = new ReturnVO(ReturnCode.FAIL);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            result = new ReturnVO(ReturnCode.FAIL);
        }
        return result;
    }
}
